// WebSocket 模拟类
export class MockWebSocket {
  private listeners: { [key: string]: Function[] } = {}
  private isConnected = false
  private reconnectTimer: number | null = null
  private heartbeatTimer: number | null = null

  constructor(private url: string) {
    this.connect()
  }

  // 连接
  connect() {
    console.log('WebSocket 连接中...', this.url)
    
    // 模拟连接延迟
    setTimeout(() => {
      this.isConnected = true
      this.emit('open', { type: 'open' })
      console.log('WebSocket 连接成功')
      
      // 开始心跳
      this.startHeartbeat()
      
      // 模拟接收消息
      this.startMockMessages()
    }, 1000)
  }

  // 断开连接
  disconnect() {
    this.isConnected = false
    this.stopHeartbeat()
    this.emit('close', { type: 'close' })
    console.log('WebSocket 连接已断开')
  }

  // 发送消息
  send(data: string | object) {
    if (!this.isConnected) {
      console.error('WebSocket 未连接')
      return false
    }

    const message = typeof data === 'string' ? data : JSON.stringify(data)
    console.log('发送消息:', message)
    
    // 模拟发送成功回调
    setTimeout(() => {
      this.emit('message', {
        type: 'message',
        data: JSON.stringify({
          type: 'send_success',
          messageId: Date.now().toString(),
          timestamp: new Date().toISOString()
        })
      })
    }, 100)

    return true
  }

  // 添加事件监听器
  addEventListener(event: string, callback: Function) {
    if (!this.listeners[event]) {
      this.listeners[event] = []
    }
    this.listeners[event].push(callback)
  }

  // 移除事件监听器
  removeEventListener(event: string, callback: Function) {
    if (this.listeners[event]) {
      const index = this.listeners[event].indexOf(callback)
      if (index > -1) {
        this.listeners[event].splice(index, 1)
      }
    }
  }

  // 触发事件
  private emit(event: string, data: any) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(data))
    }
  }

  // 开始心跳
  private startHeartbeat() {
    this.heartbeatTimer = window.setInterval(() => {
      if (this.isConnected) {
        this.send({ type: 'ping', timestamp: Date.now() })
      }
    }, 30000) // 30秒心跳
  }

  // 停止心跳
  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 模拟接收消息
  private startMockMessages() {
    // 模拟好友上线消息
    setTimeout(() => {
      this.emit('message', {
        type: 'message',
        data: JSON.stringify({
          type: 'friend_online',
          userId: 'user-1',
          timestamp: new Date().toISOString()
        })
      })
    }, 5000)

    // 模拟接收聊天消息
    setTimeout(() => {
      this.emit('message', {
        type: 'message',
        data: JSON.stringify({
          type: 'chat_message',
          messageId: Date.now().toString(),
          senderId: 'user-1',
          receiverId: 'current-user',
          content: '你好，这是一条模拟消息！',
          timestamp: new Date().toISOString()
        })
      })
    }, 10000)

    // 模拟好友请求
    setTimeout(() => {
      this.emit('message', {
        type: 'message',
        data: JSON.stringify({
          type: 'friend_request',
          requestId: Date.now().toString(),
          fromUserId: 'user-new-2',
          fromUsername: 'newuser2',
          fromNickname: '新用户2',
          fromAvatar: '/avatars/new2.jpg',
          message: '你好，我想加你为好友',
          timestamp: new Date().toISOString()
        })
      })
    }, 15000)
  }

  // 获取连接状态
  get readyState() {
    return this.isConnected ? 1 : 0 // 1: OPEN, 0: CONNECTING
  }
}

// WebSocket 管理器
export class WebSocketManager {
  private ws: MockWebSocket | null = null
  private messageHandlers: { [key: string]: Function[] } = {}
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectDelay = 1000

  constructor(private url: string) {}

  // 连接
  connect() {
    if (this.ws && this.ws.readyState === 1) {
      console.log('WebSocket 已连接')
      return
    }

    this.ws = new MockWebSocket(this.url)
    
    this.ws.addEventListener('open', this.handleOpen.bind(this))
    this.ws.addEventListener('message', this.handleMessage.bind(this))
    this.ws.addEventListener('close', this.handleClose.bind(this))
    this.ws.addEventListener('error', this.handleError.bind(this))
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.disconnect()
      this.ws = null
    }
  }

  // 发送消息
  send(data: any) {
    if (this.ws && this.ws.readyState === 1) {
      return this.ws.send(data)
    }
    console.error('WebSocket 未连接，无法发送消息')
    return false
  }

  // 添加消息处理器
  onMessage(type: string, handler: Function) {
    if (!this.messageHandlers[type]) {
      this.messageHandlers[type] = []
    }
    this.messageHandlers[type].push(handler)
  }

  // 移除消息处理器
  offMessage(type: string, handler: Function) {
    if (this.messageHandlers[type]) {
      const index = this.messageHandlers[type].indexOf(handler)
      if (index > -1) {
        this.messageHandlers[type].splice(index, 1)
      }
    }
  }

  // 处理连接打开
  private handleOpen(event: any) {
    console.log('WebSocket 连接已建立')
    this.reconnectAttempts = 0
    this.emit('connected', event)
  }

  // 处理消息
  private handleMessage(event: any) {
    try {
      const data = JSON.parse(event.data)
      console.log('收到消息:', data)
      
      // 触发对应类型的处理器
      if (this.messageHandlers[data.type]) {
        this.messageHandlers[data.type].forEach(handler => handler(data))
      }
      
      // 触发通用消息处理器
      this.emit('message', data)
    } catch (error) {
      console.error('解析消息失败:', error)
    }
  }

  // 处理连接关闭
  private handleClose(event: any) {
    console.log('WebSocket 连接已关闭')
    this.emit('disconnected', event)
    
    // 尝试重连
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
      
      setTimeout(() => {
        this.connect()
      }, this.reconnectDelay * this.reconnectAttempts)
    } else {
      console.error('重连失败，已达到最大重连次数')
      this.emit('reconnect_failed', event)
    }
  }

  // 处理错误
  private handleError(event: any) {
    console.error('WebSocket 错误:', event)
    this.emit('error', event)
  }

  // 事件发射器
  private eventListeners: { [key: string]: Function[] } = {}

  on(event: string, callback: Function) {
    if (!this.eventListeners[event]) {
      this.eventListeners[event] = []
    }
    this.eventListeners[event].push(callback)
  }

  off(event: string, callback: Function) {
    if (this.eventListeners[event]) {
      const index = this.eventListeners[event].indexOf(callback)
      if (index > -1) {
        this.eventListeners[event].splice(index, 1)
      }
    }
  }

  private emit(event: string, data: any) {
    if (this.eventListeners[event]) {
      this.eventListeners[event].forEach(callback => callback(data))
    }
  }

  // 获取连接状态
  get isConnected() {
    return this.ws ? this.ws.readyState === 1 : false
  }
}

// 创建全局 WebSocket 管理器实例
export const wsManager = new WebSocketManager('ws://localhost:8080/ws')
